package com.ljkj.blockpay.network.interceptor;

import android.os.Build;
import android.text.TextUtils;

import com.ljkj.blockpay.basedata.BuildConfig;
import com.ljkj.blockpay.network.HttpUrlHelper;
import com.ljkj.blockpay.util.GlobalContext;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Locale;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 *
 * header拦截器
 *
 */
public class HttpNetParamsInterceptor implements Interceptor {

    private static String sUserAgent;

    @Override
    public Response intercept(Chain chain) throws IOException {
        return chain.proceed(reWriteRequest(chain.request()));
    }



    private Request reWriteRequest(Request request) throws IOException{
        Request.Builder builder = request.newBuilder();
        builder.header("User-Agent", getUserAgent());
//        builder.header("Authorization", VivaPrefUtil.getAccessToken());
//        builder.header("userId", getUserIdOrVidValue());
        builder.header("Content-Type", "application/json");
        int maxStale = 60 * 60 * 24 * 7; // tolerate 1-week stale
        builder.header("Cache-Control", "no-cache");
        if (BuildConfig.getToken() != null &&!BuildConfig.getToken().equals("")){
            builder.addHeader("x-token",BuildConfig.getToken());
        }else{
            builder.removeHeader("x-token");
        }
        String url = request.url().toString();
        url = HttpUrlHelper.getValidUrl(url);
        builder.url(url);
        return builder.build();
    }

    private static String getUserAgent() {
        if (!TextUtils.isEmpty(sUserAgent)) {
            return sUserAgent;
        }
        String webUserAgent = null;
        try {
            Class<?> sysResCls = Class.forName("com.android.internal.R$string");
            Field webUserAgentField = sysResCls.getDeclaredField("web_user_agent");
            Integer resId = (Integer) webUserAgentField.get(null);
            webUserAgent = GlobalContext.getAppContext().getString(resId);
        } catch (Exception e) {
            // We have nothing to do
        }
        if (TextUtils.isEmpty(webUserAgent)) {
            webUserAgent = "Mozilla/5.0 (Linux; U; Android %s) AppleWebKit/533.1 (KHTML, like Gecko) Version/5.0 %sSafari/533.1";
        }

        Locale locale = Locale.getDefault();
        StringBuffer buffer = new StringBuffer();
        // Add version
        final String version = Build.VERSION.RELEASE;
        if (version.length() > 0) {
            buffer.append(version);
        } else {
            // default to "1.0"
            buffer.append("1.0");
        }
        buffer.append("; ");
        final String language = locale.getLanguage();
        if (language != null) {
            buffer.append(language.toLowerCase(locale));
            final String country = locale.getCountry();
            if (!TextUtils.isEmpty(country)) {
                buffer.append("-");
                buffer.append(country.toLowerCase(locale));
            }
        } else {
            // default to "en"
            buffer.append("en");
        }
        // add the model for the release build
        if ("REL".equals(Build.VERSION.CODENAME)) {
            final String model = Build.MODEL;
            if (model.length() > 0) {
                buffer.append("; ");
                buffer.append(model);
            }
        }
        final String id = Build.ID;
        if (id.length() > 0) {
            buffer.append(" Build/");
            buffer.append(id);
        }
        sUserAgent = String.format(webUserAgent, buffer, "Mobile ");
        return sUserAgent;
    }
}
